package cn.chenyumeng.blog.interceptor;

import cn.chenyumeng.blog.exception.CustomException;
import cn.chenyumeng.blog.service.admin.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @program: blog->LoginInterceptor
 * @description: 登录拦截器
 * @author: cg
 * @create: 2020-07-27 11:33
 **/
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws CustomException {
        String token = request.getParameter("Token");
        String userId = request.getParameter("UserId");
        if (token == null || "".equals(token) || userId == null || "".equals(userId)) {
            throw new CustomException("请先登录！");
        }
        if (!userService.hasUser(token, Long.parseLong(userId))) {
            throw new CustomException("请先登录");
        }
        return true;
    }
}
